package cn.smartorigin.soas.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterJob;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import cn.smartorigin.soas.data.SqliteConnecter;
import cn.smartorigin.soas.data.TestData;
import cn.smartorigin.soas.frame.menubar.CellMenu;
import cn.smartorigin.soas.frame.menubar.CellMenuBar;
import cn.smartorigin.soas.frame.menubar.CellMenuItem;
import cn.smartorigin.soas.frame.panel.CellClientMainPagePanel;
import cn.smartorigin.soas.frame.panel.CellPagePanel;
import cn.smartorigin.soas.frame.panel.CellTablePanel;
import cn.smartorigin.soas.frame.panel.ManageClientPage;
import cn.smartorigin.soas.frame.panel.ManagePlateTypePage;
import cn.smartorigin.soas.frame.statusbar.StatusBar;
import cn.smartorigin.soas.frame.statusbar.StatusLabel;
import cn.smartorigin.soas.frame.statusbar.StatusTimeLabel;
import cn.smartorigin.soas.frame.tab.CellTabComponent;
import cn.smartorigin.soas.frame.tab.CellTabbedPane;
import cn.smartorigin.soas.frame.tree.CellMutableTreeNode;
import cn.smartorigin.soas.frame.xml.XmlUtil;


public class MainFrame extends JFrame{
	
	/**
	 * 
	 */
//	private String[] TABLE_HEAD = {"ID号","日期", "编号" ,"品名","价格","数量","总价", "客户名称"};
	private String MENU_BAR_XML = "res/values/menubar.xml";
	MainFrameActionListener mfaction = new MainFrameActionListener();
	
	private CellMenuBar xxmenubar = XmlUtil.loadMenuBar(MENU_BAR_XML, mfaction);
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel leftPanel, rightPanel;
	
	StatusBar mStatusBar;

	public  SqliteConnecter mSQLite;
	
	JScrollPane mClistPanel, clntListPanel;
	JColorList mCDataList, cmpyMgList, mPrdctList;

	JTabbedPane tabs;
    private CellTabbedPane cellTab = new CellTabbedPane();
//	JPanel p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12 ;
//	JColorTable   cTable;	
//	DefaultTableModel model;

	
	//JButton mAddOrderBtn, mPrintBtn;

	
	/**
	 * JTree
	 */
	JTree tree1,tree2;
	DefaultMutableTreeNode mClientTree;
	CellMutableTreeNode mercury ;
	CellMutableTreeNode mars ;
	CellMutableTreeNode venus;
	String MARS = "客户管理";
	String MERCURY = "主页";
	String VENUS = "镀种管理";
	
	/**
	 *  menu item
	 */
//	CellMenuItem mAddClientItem ,mAddProductItem, mAddOrderItem, mLoginItem;
	
	
	class SosaEnv{
		private int selectedTab; // 0~12
		private int selectedListIndex;
		private String selectedListValue;
		
		// tab
		private int function_tab_today;
		private int function_tab_platetype;
		private int funciont_tab_client;
		private int[] current_tab_array;
		
		
		public SosaEnv(){
			selectedTab = 0;
			selectedListIndex =0;
			selectedListValue = "主页";
			
			function_tab_today 		= 0;
			function_tab_platetype 	= 0;
			funciont_tab_client 	= 0;
			
			current_tab_array = new int[200];
			initTabArray();
		}
		
		public String getSelectedListValue() {
			return selectedListValue;
		}

		public void setSelectedListValue(String selectedListItem) {
			this.selectedListValue = selectedListItem;
		}
		
		public int getSelectedTab() {
			return selectedTab;
		}

		public void setSelectedTab(int selectedTab) {
			this.selectedTab = selectedTab;
		}
		
		/**
		 * 
		 */
		private void initTabArray(){
			for(int i=0; i<current_tab_array.length; i++){
				clrTabExsitId(i);
			}
		}
		
		/**
		 * 查询当前tab id 是否存在
		 */
		public void setTabExsitId(int usrId){
			current_tab_array[usrId] = 1;
		}
		
		public void clrTabExsitId(int usrId){
			current_tab_array[usrId] = 0;
		}
		
		/**
		 * 查询当前tab id 是否存在
		 */
		public boolean isTabExsit(int usrId){
			if (current_tab_array[usrId] == 1) {
				return true;
			}
			return false;
		}
		
		/**
		 * 
		 */
		public void setFunctionTabToady(int statu){
			this.funciont_tab_client = statu;
		}
		
		public int getFunctionTabToady(){
			return this.funciont_tab_client ;
		}


	}
	
	SosaEnv mSosaEnv;
	
	public MainFrame(){
		this.setTitle("SOAS - Statement Of Account System");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		this.setIconImage(new ImageIcon("img/sosa_logo.png").getImage());
//		this.setSize(getMaximumSize());
//		this.tabPanelInit();
//		this.tableInit();
		this.envInit();
		this.initFont();
		this.initSQLite();
		this.initLayout();

		
//		testSQLite();
		
		this.setVisible(true);
	}
	
	private void envInit(){
		mSosaEnv = new SosaEnv();
	}
	
	private void initFont(){
		Font font = new Font("宋体", Font.PLAIN, 12);
		UIManager.put("Button.font", font);
		UIManager.put("Menu.font", font);
		UIManager.put("MenuItem.font", font);
		UIManager.put("List.font", font);
		UIManager.put("Table.font", font);
		UIManager.put("TabbedPane.font", font);
		UIManager.put("Label.font", font);

	}
	
	/**
	 * initial SQLite
	 */
	private void initSQLite(){
		try {
			mSQLite = new SqliteConnecter();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * initial main frame module <p>
	 * initial menu <br>
	 * initial tab <br>
	 * initial statusbar <br>
	 */
	private void initLayout(){
	
		leftPanel = new JPanel();
		leftPanel.setBackground(Color.white);
		leftPanel.setLayout(new  BorderLayout());
		
		rightPanel= new JPanel();
		rightPanel.setBackground(Color.gray);
		//rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		rightPanel.setLayout(new BorderLayout());
		
		statusBarInit();

		this.getContentPane().add(leftPanel, BorderLayout.WEST);
		this.getContentPane().add(rightPanel, BorderLayout.CENTER);
		this.getContentPane().add(mStatusBar, BorderLayout.SOUTH);


		this.listInit();
		initControlTree();
		
		
		// right panel
		this.tabPanelInit();
//		this.initFunBtnPanel();
		
		// menu
		this.menuBarInit();

	}
	
	/**
	 * 初始化 全局控制功能树，如企业管理、客户管理等等呢
	 */
	private void initControlTree() {
			
		DefaultMutableTreeNode mControlTree = new DefaultMutableTreeNode("企业管理");
		mercury = new CellMutableTreeNode(MERCURY, 1);
		mars = new CellMutableTreeNode(MARS, 2);
		venus = new CellMutableTreeNode(VENUS, 3);
		mControlTree.add(mercury);
		mControlTree.add(mars);
		mControlTree.add(venus);

		tree1 = new JTree(mControlTree);
		tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); 
		tree1.addMouseListener(new ClientTreeListener());
//		tree1.setUI(ui);
		
		tree2 = new JTree(mClientTree);
		tree2.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); 
		tree2.addMouseListener(new ClientTreeListener()); 
		
		DefaultTreeCellRenderer  cellRenderer = (DefaultTreeCellRenderer) tree1.getCellRenderer();
		cellRenderer.setOpenIcon(new ImageIcon("res/images/user_product.png"));
		cellRenderer.setClosedIcon(new ImageIcon("res/images/user_product.png"));
		cellRenderer.setBackgroundSelectionColor(Color.gray);
		cellRenderer.setTextSelectionColor(Color.red);
		cellRenderer.setLeafIcon(new ImageIcon("res/images/user_product.png"));
		
		DefaultTreeCellRenderer  cellRenderer2 = (DefaultTreeCellRenderer) tree2.getCellRenderer();
		cellRenderer2.setOpenIcon(new ImageIcon("res/images/GameID6.png"));
		cellRenderer2.setClosedIcon(new ImageIcon("res/images/GameID6.png"));
		cellRenderer2.setLeafIcon(new ImageIcon("res/images/user.png"));
		
		this.leftPanel.add(tree1, BorderLayout.NORTH);
		this.leftPanel.add(tree2, BorderLayout.CENTER);
		
	}
	
	private void statusBarInit(){
		mStatusBar = new StatusBar();
		
		InetAddress addr;
		String ip = "";
		try {
			addr = InetAddress.getLocalHost();
			ip=addr.getHostAddress().toString();//获得本机IP
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		mStatusBar.addSeparator();
		mStatusBar.getRightPane().add(new StatusLabel(new ImageIcon("img/statusbar/net_card.png")));
		mStatusBar.getRightPane().add(new StatusLabel(ip));
		mStatusBar.addSeparator();
		mStatusBar.getRightPane().add(new StatusTimeLabel());
		mStatusBar.addSeparator();
		mStatusBar.getRightPane().add(new StatusLabel("v1.0.0"));
		mStatusBar.addSeparator();
		mStatusBar.getRightPane().add(new StatusLabel("Powered by Minkai.Gu"));
	}

	//private void companyManageListInit(){
	//	String[] testStr = {"功能一", "增加企业", "增加产品"};
	//	cmpyMgList = new JColorList();
	//	cmpyMgList.setListData(testStr);
	//}
	
	private void listInit(){
		
//		ListListener ls = new ListListener();
		
//		String[] listdata= new String[0];
		Vector v = new Vector();
		SoasUtil.TreeNodeData tnd = new SoasUtil.TreeNodeData();
		try {
			v =	TestData.getClntTblData(mSQLite);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		mClientTree = new DefaultMutableTreeNode("客户列表");
		for(int i=0; i<v.size();i++){
			tnd = (SoasUtil.TreeNodeData)v.get(i);
			CellMutableTreeNode mercury  = new CellMutableTreeNode(tnd.treeNodeName, tnd.treeNodeUsrId);
			mClientTree.add(mercury);
		}
		tnd = null;
		
	}
	
	private void listDataFlash(){
//		Vector v = new Vector();
//		try {
//			v =	TestData.getClntTblData(mSQLite);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		mCDataList.setListData(v);
		Vector v = new Vector();
		SoasUtil.TreeNodeData tnd = new SoasUtil.TreeNodeData();
		try {
			v =	TestData.getClntTblData(mSQLite);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//mClientTree = new DefaultMutableTreeNode("客户列表");
		
		mClientTree.removeAllChildren();
		for(int i=0; i<v.size();i++){
			tnd = (SoasUtil.TreeNodeData)v.get(i);
			CellMutableTreeNode mercury  = new CellMutableTreeNode(tnd.treeNodeName, tnd.treeNodeUsrId);
			mClientTree.add(mercury);
		}
		tnd = null;
		
		
//		tree2 = new JTree(mClientTree);
//		tree2.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); 
//		tree2.addMouseListener(new ClientTreeListener()); 
//		
//		DefaultTreeCellRenderer  cellRenderer2 = (DefaultTreeCellRenderer) tree2.getCellRenderer();
//		cellRenderer2.setOpenIcon(new ImageIcon("res/images/GameID6.png"));
//		cellRenderer2.setClosedIcon(new ImageIcon("res/images/GameID6.png"));
//		cellRenderer2.setLeafIcon(new ImageIcon("res/images/user.png"));
//		
//		this.leftPanel.add(tree2, BorderLayout.CENTER);
//		this.repaint();
	}
	
//	private void tableDataFlash(){
//		int tabIndex  = mSosaEnv.getSelectedTab();
//		String listValue = mSosaEnv.getSelectedListValue();
//		Object str[][]=new String[0][0];
//		Object header[]=TABLE_HEAD;
//		model = new DefaultTableModel(str,header);
//		try {
//			int clientId = TestData.getClientId(mSQLite, listValue);
//			TestData.getSelectUsrTblOrderData(mSQLite, model, clientId, tabIndex);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//        cTable.setModel(model);
//	}
	
	
	/**
	 * menu bar initial
	 */
	private void menuBarInit(){
		this.getContentPane().add(xxmenubar, BorderLayout.NORTH);	
	}
	
//	private void tableInit(){
//		Object str[][]=new String[0][0];
//		Object header[] = TABLE_HEAD;
//		model = new DefaultTableModel(str,header);
//		try {
//			TestData.getUsrTblData(mSQLite, model, mSosaEnv.getSelectedTab());
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//        cTable = new JColorTable(model);
//        mClistPanel = new JScrollPane(cTable);
//
//	}
	
	/**
	 * tab initial
	 */
	private void tabPanelInit(){
		//tabs = new JTabbedPane();
		cellTab.addTab("主页",createMainPage(), 1001);	
		cellTab.setTabPlacement(JTabbedPane.TOP);
		//rightPanel.add(tabs);
		rightPanel.add(cellTab, BorderLayout.CENTER);
		//this.tableInit();
	}
	
	public void reflashData(){
		this.listDataFlash();
	}
	
	/**
	 * initial function button panel
	 * button : add deliver
	 * button : print
	 */
//	public void initFunBtnPanel(){
		
//		BtnListener bl = new BtnListener();
		
//		JPanel pl = new JPanel();
//		pl.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		//pl.setBackground(Color.white);
		//pl.setLayout(new BoxLayout(pl, BoxLayout.X_AXIS));
//		pl.setLayout(new FlowLayout());
//		mAddOrderBtn = new JButton("添加订单");
//		mAddOrderBtn.setAlignmentX(Component.RIGHT_ALIGNMENT);
//		mAddOrderBtn.addActionListener(bl);
		
//		mPrintBtn  = new JButton("打印");
//		mPrintBtn.addActionListener(bl);
//		mPrintBtn.setAlignmentX(Component.RIGHT_ALIGNMENT);
		
//		pl.add(mAddOrderBtn);
//		pl.add(mPrintBtn);
//		this.rightPanel.add(pl, BorderLayout.PAGE_END);
//	}
	
//	class BtnListener implements ActionListener{
//		@Override
//		public void actionPerformed(ActionEvent e){
//			Object  obj =(Object)e.getSource();
//			if(obj == mAddOrderBtn){
//				new AddOrder();
//			}else if(obj == mPrintBtn){
////				PrinterJob.printDialog();
//			}
//		}
//	
//	}
	
//	class ListListener  implements  MouseListener {
//
//	@Override
//	public void mouseClicked(MouseEvent e) {
//        Object   iSelection   =   ((JList)e.getSource()).getSelectedValue(); 
//        mSosaEnv.setSelectedListValue(iSelection.toString());
//        tableDataFlash();
//	}
//
//	@Override
//	public void mousePressed(MouseEvent e) {}
//
//	@Override
//	public void mouseReleased(MouseEvent e) {}
//
//	@Override
//	public void mouseEntered(MouseEvent e) {}
//
//	@Override
//	public void mouseExited(MouseEvent e) {	}
//	
//	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//
//		new MainFrame();
//	}
	
	
	/**
	 * mainframe  menu 监听类
	 */
	class MainFrameActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			String command = e.getActionCommand();
			if (command.equals("M101")) {

			} else if (command.equals("M201")) {
				//new AddPlateTypeFrame();
			} else if (command.equals("M202")) {

			} else if (command.equals("M301")) {
				//new AddClient();
			} else if (command.equals("M302")) {

			} else if (command.equals("M303")) {
				//new AddProduct();
			} else if (command.equals("M304")) {

			} else if (command.equals("M401")) {
				//new AddOrder();
			} else if (command.equals("M402")) {

			}

		}
	}
	
	private CellClientMainPagePanel createClientMainPage(CellMutableTreeNode   selecedNode, int id){
		CellClientMainPagePanel page = new CellClientMainPagePanel(id);
		return page;
	}
	
//    private void setupPageToolbar(CellPagePanel page) {
        //page.getLeftToolBar().add(new ImageButton("res/images/home.png", "");
        //page.getLeftToolBar().add(createButton("res/images/left.png", "Click to go left", false));
        //page.getLeftToolBar().add(createButton("res/images/right.png", "Click to go right", false));

        //FreeSearchTextField txtSearch = new FreeSearchTextField();
        //txtSearch.setColumns(10);
        //page.getRightToolBar().add(txtSearch);
        //page.getRightToolBar().add(createButton("/free/test/add.png", "Click to go right", true));
        //page.getRightToolBar().add(createButton("/free/test/update.png", "Click to go right", true));
        //page.getRightToolBar().add(createButton("/free/test/refresh.png", "Click to go right", true));
        //page.getRightToolBar().add(createButton("/free/test/print.png", "Click to go right", true));
//    }
	
	private JPanel createMainPage(){
		JPanel pl = new JPanel();
		pl.setLayout(new GridLayout(3,2));
		
		return pl;
	}
	

	class ClientTreeListener  implements  MouseListener {

		@Override
		public void mouseClicked(MouseEvent e) {
			if(e.getClickCount()==2){
				Object obj = e.getSource();
				if(obj == tree1){
					CellMutableTreeNode   selecedNode   = (CellMutableTreeNode)tree1.getLastSelectedPathComponent();
					if(selecedNode.toString().endsWith(MARS)){
						if(cellTab.getTabId(1002)==false){
							ManageClientPage pl = new ManageClientPage(MainFrame.this);
							cellTab.addTab(selecedNode.toString(), pl, 1002);
							cellTab.setSelectedComponent(pl);
						}else{
							cellTab.setSelectTab(1002);
						}
						
					}else if(selecedNode.toString().endsWith(VENUS)){
						if(cellTab.getTabId(1003)==false){
							ManagePlateTypePage pl = new ManagePlateTypePage();
							cellTab.addTab(selecedNode.toString(), pl, 1003);
							cellTab.setSelectedComponent(pl);
						}else{
							cellTab.setSelectTab(1003);
						}
					}else if(selecedNode.toString().endsWith(MERCURY)){
						if(cellTab.getTabId(1001)==false){
							JPanel pl = createMainPage();
							cellTab.addTab(selecedNode.toString(), pl, 1001);
							cellTab.setSelectedComponent(pl);
						}else{
							cellTab.setSelectTab(1001);
						}
					}
				}else if(obj==tree2){
					CellMutableTreeNode   selecedNode   = (CellMutableTreeNode)tree2.getLastSelectedPathComponent();
					int usrId = selecedNode.getUsrId();
					
						if(cellTab.getTabId(usrId)==false){
							//CellTablePanel pl = createClientListTab(selecedNode, usrId);
							CellClientMainPagePanel pl = createClientMainPage(selecedNode, usrId);
							cellTab.addTab(selecedNode.toString(), pl, usrId);
							cellTab.setSelectedComponent(pl);
						}else{
							cellTab.setSelectTab(usrId);
						}
				}
				
			}
		}

		@Override
		public void mousePressed(MouseEvent e) { 
		}
		
		@Override
		public void mouseReleased(MouseEvent e) { 
		}

		@Override
		public void mouseEntered(MouseEvent e) { 
		}

		@Override
		public void mouseExited(MouseEvent e) { 
		}
		
	}
	
	

}
